import os
import time
import random
import logging
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from PIL import Image, ImageDraw, ImageFont
import textwrap
import requests
from io import BytesIO

# 配置日志
logging.basicConfig(
    filename='hotspot.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)


class BaiduHotspotCrawler:
    def __init__(self):
        self.chrome_options = webdriver.ChromeOptions()
        self._setup_chrome_options()

        self.driver = webdriver.Chrome(
            executable_path='D:\software\chromedriver133\chromedriver-win64\chromedriver-win64\chromedriver',
            options=self.chrome_options
        )
        self.driver.set_window_size(1920, 1080)

    def _setup_chrome_options(self):
        """配置浏览器选项"""
        self.chrome_options.add_argument("--headless")
        self.chrome_options.add_argument("--disable-gpu")
        # self.chrome_options.add_argument("--no-sandbox")
        # self.chrome_options.add_argument("--disable-dev-shm-usage")
        # self.chrome_options.add_argument("--remote-debugging-port=65464")
        # self.chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        # self.chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")

    def fetch_hotspots(self):
        """获取完整热搜数据"""
        try:
            self.driver.get("https://top.baidu.com/board?tab=realtime")
            WebDriverWait(self.driver, 15).until(
                EC.presence_of_element_located((By.CLASS_NAME, "category-wrap_iQLoo"))
            )
            time.sleep(3 + random.random() * 2)  # 模拟人工等待

            hotspots = []
            items = self.driver.find_elements(By.CLASS_NAME, "category-wrap_iQLoo")
            for item in items[:20]:  # 取前20条
                try:
                    title = item.find_element(By.CLASS_NAME, 'c-single-text-ellipsis').text
                    hot = item.find_element(By.CLASS_NAME, 'hot-index_1Bl1a').text
                    desc = item.find_element(By.CLASS_NAME, 'hot-desc_1m_jR').text
                    link = item.find_element(By.TAG_NAME, 'a').get_attribute('href')
                    cover = item.find_element(By.TAG_NAME, 'img').get_attribute('src')

                    hotspots.append({
                        'title': title,
                        'hot': self._parse_hot(hot),
                        'desc': desc,
                        'url': link,
                        'cover': cover
                    })
                except Exception as e:
                    logging.warning(f"解析条目失败: {str(e)}")
            return hotspots
        except Exception as e:
            logging.error(f"爬取失败: {str(e)}")
            return []
        finally:
            self.driver.quit()

    def _parse_hot(self, hot_str):
        """解析热度数值"""
        try:
            return int(hot_str.replace('万', '0000').replace('亿', '00000000'))
        except:
            return 0


class ContentGenerator:
    def __init__(self):
        self.font_path = "simhei.ttf"
        self.template_size = (1080, 1920)  # 抖音竖屏尺寸

    def generate(self, hotspot):
        """生成完整内容"""
        try:
            # 生成标题
            title = f"🔥{hotspot['title']} | 百度热搜 {self._format_hot(hotspot['hot'])}"

            # 生成文案
            content = self._generate_content(hotspot)

            # 生成图片
            image = self._generate_image(hotspot, title)

            return {
                'title': title,
                'content': content,
                'image_path': image,
                'tags': ['百度热搜', '热门话题', '时事新闻']
            }
        except Exception as e:
            logging.error(f"内容生成失败: {str(e)}")
            return None

    def _generate_content(self, hotspot):
        """生成文字内容"""
        return f"""【全网热议】{hotspot['title']}

📈实时热度：{self._format_hot(hotspot['hot'])}
📌事件背景：{hotspot['desc'][:60]}...
👉点击查看详情：{hotspot['url']}

#热点 #新闻 #热门话题
"""

    def _generate_image(self, hotspot, title):
        """生成封面图"""
        try:
            # 下载封面图
            response = requests.get(hotspot['cover'], timeout=10)
            cover_img = Image.open(BytesIO(response.content)).convert("RGB")
            cover_img = self._resize_cover(cover_img)

            # 创建背景图
            bg = Image.new('RGB', self.template_size, (20, 20, 20))
            bg.paste(cover_img, (240, 300))

            # 添加标题文字
            draw = ImageDraw.Draw(bg)
            font = ImageFont.truetype(self.font_path, 42)
            self._draw_text(draw, title, (100, 750), font, max_width=25)

            # 添加热度标识
            hot_text = f"🔥 实时热度：{self._format_hot(hotspot['hot'])}"
            self._draw_text(draw, hot_text, (100, 1000), ImageFont.truetype(self.font_path, 36))

            # 保存临时文件
            os.makedirs("output", exist_ok=True)
            image_path = f"output/{datetime.now().strftime('%Y%m%d%H%M%S')}.jpg"
            bg.save(image_path)
            return image_path
        except Exception as e:
            logging.error(f"图片生成失败: {str(e)}")
            return None

    def _resize_cover(self, img):
        """调整封面图尺寸"""
        target_size = (600, 400)
        return img.resize(target_size, Image.Resampling.LANCZOS)

    def _draw_text(self, draw, text, position, font, max_width=20, color=(255, 255, 0)):
        """绘制自动换行文本"""
        lines = textwrap.wrap(text, width=max_width)
        x, y = position
        for line in lines:
            draw.text((x, y), line, font=font, fill=color)
            y += font.getsize(line)[1] + 10

    def _format_hot(self, hot_num):
        """格式化热度显示"""
        if hot_num >= 100000000:
            return f"{hot_num / 100000000:.1f}亿"
        elif hot_num >= 10000:
            return f"{hot_num / 10000:.1f}万"
        return str(hot_num)


class DouyinPublisher:
    def __init__(self):
        self.driver = None
        self._init_browser()

    def _init_browser(self):
        """初始化浏览器"""
        options = webdriver.ChromeOptions()
        options.add_argument("--disable-notifications")
        #options.add_argument("user-data-dir=./chrome_profile")  # 保存登录状态
        options.add_argument("--disable-gpu")
        self.driver = webdriver.Chrome(
            executable_path='D:\software\chromedriver133\chromedriver-win64\chromedriver-win64\chromedriver',
            options=options
        )
        self.driver.implicitly_wait(200)

    def upload_content(self, content):
        """发布内容到抖音"""
        try:
            self._check_login()
            self._navigate_to_upload()
            self._upload_image(content['image_path'])
            self._fill_content(content)
            self._submit_post()
            return True
        except Exception as e:
            logging.error(f"发布失败: {str(e)}")
            return False

    def _check_login(self):
        """检查登录状态"""
        self.driver.get("https://creator.douyin.com/creator-micro/content/upload")
        if "creator" in self.driver.current_url:
            input("请手动扫码登录后按回车继续...")

    def _navigate_to_upload(self):
        """跳转到发布页面"""
        self.driver.get("https://creator.douyin.com/creator-micro/content/upload?default-tab=3")
        WebDriverWait(self.driver, 20).until(
            EC.presence_of_element_located((By.XPATH, '//input[@type="file"]'))
        )

    def _upload_image(self, image_path):
        """上传图片"""
        upload_input = self.driver.find_element(By.XPATH, '//input[@type="file"]')
        upload_input.send_keys(os.path.abspath(image_path))
        time.sleep(3 + random.random() * 2)  # 等待上传完成

    def _fill_content(self, content):
        """填写内容"""
        # 输入标题
        title_box = self.driver.find_element(By.TAG_NAME, 'textarea')
        title_box.send_keys(f"{content['title']}\n\n{content['content']}")

        # 添加标签
        for tag in content['tags']:
            self.driver.find_element(By.CLASS_NAME, 'zone-container').send_keys(f" #{tag}")

    def _submit_post(self):
        """提交发布"""
        submit_btn = WebDriverWait(self.driver, 15).until(
            EC.element_to_be_clickable((By.XPATH, '//button[contains(text(), "发布")]')))
        submit_btn.click()
        time.sleep(5)

if __name__ == "__main__":
    #执行流程
    crawler = BaiduHotspotCrawler()
    hotspots = crawler.fetch_hotspots()

    generator = ContentGenerator()
    publisher = DouyinPublisher()

    for idx, hotspot in enumerate(hotspots[:5]):  # 每次处理前5条
        content = generator.generate(hotspot)
    if content:
        print(content)
        result = publisher.upload_content(content)
    #logging.info(f"发布结果：{'成功' if result else '失败'} - {hotspot['title']}")
    #time.sleep(300 + random.randint(60, 120))  # 控制发布频率